package com.xzmzhp.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author: 王源(xm)
 * @create: 2021-06-08 14:15
 * @program: ams
 * @description: 权限决策器
 */
@Component
public class RoleAccessDecisionManager implements AccessDecisionManager {
    /**
     * decide 方法是判定是否拥有权限的决策方法，
     *
     * @param authentication 当前用户的信息
     * @param o              包含客户端发起的请求的requset信息
     * @param collection     当前路径对应的权限
     * @throws AccessDeniedException               安全异常
     * @throws InsufficientAuthenticationException 安全异常
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        LoginUser loginUser = null;
        if (authentication.getPrincipal() instanceof LoginUser) {
            loginUser = (LoginUser) authentication.getPrincipal();
        }
        for (ConfigAttribute c : collection) {
            if (loginUser != null && c.getAttribute().equals(loginUser.getUser().getCompetenceName())) {
                return;
            }
        }
        throw new AccessDeniedException("当前访问没有权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
